package com.code.wflow.utils;

import com.alibaba.fastjson2.JSON;
import com.code.wflow.bo.FormItemBO;
import com.code.wflow.formitem.FormItemProperties;
import com.code.wflow.model.FormItem;
import com.code.wflow.vo.FormItemVO;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ggh
 * @date 2023/2/23
 * 表单解析
 */
public class FormItemUtils {
    /**
     * 解析表单定义
     *
     * @param formItems
     * @return
     */
    public static List<FormItem> parseFormItems(String formItems) {
        if (StringUtils.isEmpty(formItems)) {
            return null;
        }

        List<FormItemBO> formItemBOList = JSON.parseArray(formItems, FormItemBO.class);
        List<FormItem> formItemList = new ArrayList<>(formItemBOList.size());
        formItemBOList.forEach((bo) -> {
            FormItem formItem = BeanCopierUtils.copy(bo, FormItem.class);
            formItem.setCode(bo.getId());
            formItemList.add(formItem);
        });
        return formItemList;
    }

    /**
     * 构建流程定义
     *
     * @param formItemList
     * @return
     */
    public static String buildFormItemDef(List<FormItem> formItemList) {
        if (CollectionUtils.isEmpty(formItemList)) {
            return null;
        }
        List<FormItemVO> formItemVOList = itemToVO(formItemList);
        return JSON.toJSONString(formItemVOList);
    }

    private static List<FormItemVO> itemToVO(List<FormItem> itemList) {
        List<FormItemVO> itemVOList = new ArrayList<>(itemList.size());
        for (FormItem item : itemList) {
            FormItemVO itemVO = new FormItemVO();
            itemVO.setId(item.getCode());
            itemVO.setIcon(item.getIcon());
            itemVO.setTitle(item.getTitle());
            itemVO.setValueType(item.getValueType());

            FormItemProperties prop = JSON.parseObject(item.getProps(), FormItemProperties.class);
            itemVO.setProps(prop);
            itemVOList.add(itemVO);
        }
        return itemVOList;
    }
}
